<template>
  <PageLayout
    title="主机类型管理"
    subtitle="管理系统中的主机类型，包括图标、颜色等配置"
    icon="fa fa-tags"
    class="apply-glass-theme"
  >
    <template #toolbar-left>
      <el-button type="primary" @click="showCreateDialog" class="tech-button">
        <i class="fa fa-plus"></i> 新建类型
      </el-button>
    </template>

    <!-- 主要内容 -->
    <template #content>
      <el-table
        :data="hostTypes"
        v-loading="loading"
        class="glass-dialog tech-table"
        stripe
        border
        style="width: 100%;"
      >
        <el-table-column prop="name" label="类型名称" width="120" align="center">
          <template #default="scope">
            <el-tag size="small">{{ scope.row.name }}</el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="display_name" label="显示名称" width="150" align="center" />
        
        <el-table-column label="图标" width="80" align="center">
          <template #default="scope">
            <i :class="`fas ${scope.row.icon}`" :style="{ color: scope.row.color, fontSize: '18px' }"></i>
          </template>
        </el-table-column>
        
        <el-table-column label="颜色" width="100" align="center">
          <template #default="scope">
            <div class="color-display">
              <div 
                class="color-box" 
                :style="{ backgroundColor: scope.row.color }"
              ></div>
              <span class="color-text">{{ scope.row.color }}</span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="description" label="描述" min-width="200" />
        
        <el-table-column label="类型" width="100" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.is_system ? 'info' : 'success'" size="small">
              {{ scope.row.is_system ? '系统内置' : '自定义' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="创建时间" width="180" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.created_at) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="150" align="center" fixed="right">
          <template #default="scope">
            <div class="action-buttons">
              <el-button
                type="warning"
                size="small"
                @click="editHostType(scope.row)"
                class="action-btn"
              >
                <i class="fa fa-edit"></i>
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="deleteHostType(scope.row)"
                class="action-btn"
              >
                <i class="fa fa-trash"></i>
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <!-- 对话框 -->
    <template #dialogs>
      <!-- 创建/编辑主机类型对话框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="isEdit ? '编辑主机类型' : '新建主机类型'"
        width="600px"
        class="tech-dialog"
        :close-on-click-modal="false"
      >
        <el-form :model="hostTypeForm" :rules="formRules" ref="hostTypeFormRef" label-width="100px" class="tech-form">
          <el-form-item label="类型名称" prop="name">
            <el-input
              v-model="hostTypeForm.name"
              placeholder="请输入类型名称（英文字母和数字）"
            />
          </el-form-item>

          <el-form-item label="显示名称" prop="display_name">
            <el-input
              v-model="hostTypeForm.display_name"
              placeholder="请输入显示名称"
            />
          </el-form-item>

          <el-form-item label="图标" prop="icon">
            <div class="icon-selector">
              <el-input
                v-model="hostTypeForm.icon"
                placeholder="请选择图标"
                readonly
              >
                <template #prepend>
                  <i :class="`fas ${hostTypeForm.icon}`" v-if="hostTypeForm.icon"></i>
                </template>
              </el-input>
              <div class="icon-grid">
                <div
                  v-for="icon in iconOptions"
                  :key="icon"
                  class="icon-option"
                  :class="{ active: hostTypeForm.icon === icon }"
                  @click="hostTypeForm.icon = icon"
                >
                  <i :class="`fas ${icon}`"></i>
                </div>
              </div>
            </div>
          </el-form-item>

          <el-form-item label="颜色" prop="color">
            <div class="color-selector">
              <el-color-picker
                v-model="hostTypeForm.color"
                :predefine="colorPresets"
                @change="handleColorChange"
              />
              <el-input
                v-model="hostTypeForm.color"
                placeholder="#409EFF"
                style="margin-left: 10px; width: 120px;"
              />
            </div>
          </el-form-item>

          <el-form-item label="描述" prop="description">
            <el-input
              v-model="hostTypeForm.description"
              type="textarea"
              :rows="3"
              placeholder="请输入类型描述"
            />
          </el-form-item>
        </el-form>
      
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogVisible = false">
              取消
            </el-button>
            <el-button
              type="primary"
              @click="submitForm"
              :loading="submitting"
            >
              {{ isEdit ? '更新' : '创建' }}
            </el-button>
          </div>
        </template>
      </el-dialog>
    </template>
  </PageLayout>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import PageLayout from '@/components/PageLayout.vue'

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const dialogVisible = ref(false)
const isEdit = ref(false)
const hostTypes = ref([])
const hostTypeFormRef = ref()

// 表单数据
const hostTypeForm = reactive({
  name: '',
  display_name: '',
  icon: '',
  color: '#409EFF',
  description: '',
  is_system: false
})

// 图标选项
const iconOptions = [
  'fa-server', 'fa-database', 'fa-globe', 'fa-memory', 'fa-balance-scale',
  'fa-chart-line', 'fa-cloud', 'fa-desktop', 'fa-laptop', 'fa-mobile-alt',
  'fa-network-wired', 'fa-wifi', 'fa-shield-alt', 'fa-lock', 'fa-key',
  'fa-cog', 'fa-tools', 'fa-wrench', 'fa-bug', 'fa-fire',
  'fa-bolt', 'fa-rocket', 'fa-cube', 'fa-cubes', 'fa-layer-group'
]

// 颜色预设
const colorPresets = [
  '#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399',
  '#9C27B0', '#FF5722', '#795548', '#607D8B', '#00BCD4'
]

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入类型名称', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9]+$/, message: '类型名称只能包含字母和数字', trigger: 'blur' }
  ],
  display_name: [
    { required: true, message: '请输入显示名称', trigger: 'blur' }
  ],
  icon: [
    { required: true, message: '请选择图标', trigger: 'change' }
  ],
  color: [
    { required: true, message: '请选择颜色', trigger: 'change' },
    { pattern: /^#[0-9A-Fa-f]{6}$/, message: '请输入有效的十六进制颜色值', trigger: 'blur' }
  ]
}

// 方法
const fetchHostTypes = async () => {
  loading.value = true
  try {
    const response = await axios.get('/api/hosttypes/')
    console.log('主机类型API响应:', response.data)

    // 处理分页响应或直接数组响应
    let typeData = response.data
    if (typeData && typeof typeData === 'object' && typeData.results) {
      // 分页响应
      typeData = typeData.results
    }

    // 确保是数组并过滤掉无效的主机类型数据
    if (Array.isArray(typeData)) {
      hostTypes.value = typeData.filter(type => type && type.id)
    } else {
      console.warn('主机类型数据不是数组格式:', typeData)
      hostTypes.value = []
    }
  } catch (error) {
    console.error('获取主机类型失败:', error)
    ElMessage.error('获取主机类型失败')
    hostTypes.value = []
  } finally {
    loading.value = false
  }
}

const showCreateDialog = () => {
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

const editHostType = (hostType) => {
  isEdit.value = true
  Object.assign(hostTypeForm, hostType)
  dialogVisible.value = true
}

const resetForm = () => {
  Object.assign(hostTypeForm, {
    name: '',
    display_name: '',
    icon: '',
    color: '#409EFF',
    description: '',
    is_system: false
  })
  if (hostTypeFormRef.value) {
    hostTypeFormRef.value.clearValidate()
  }
}

const submitForm = async () => {
  if (!hostTypeFormRef.value) return
  
  try {
    await hostTypeFormRef.value.validate()
    submitting.value = true
    
    if (isEdit.value) {
      await axios.put(`/api/hosttypes/${hostTypeForm.id}/`, hostTypeForm)
      ElMessage.success('主机类型更新成功')
    } else {
      await axios.post('/api/hosttypes/', hostTypeForm)
      ElMessage.success('主机类型创建成功')
    }
    
    dialogVisible.value = false
    await fetchHostTypes()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error(isEdit.value ? '主机类型更新失败' : '主机类型创建失败')
  } finally {
    submitting.value = false
  }
}

const deleteHostType = async (hostType) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除主机类型 "${hostType.display_name}" 吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        customClass: 'tech-message-box'
      }
    )

    await axios.delete(`/api/hosttypes/${hostType.id}/`)
    ElMessage.success('主机类型删除成功')
    await fetchHostTypes()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('主机类型删除失败')
    }
  }
}

const formatDate = (dateString) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleString('zh-CN')
}

// 处理颜色变化，确保输出16进制格式
const handleColorChange = (color) => {
  if (color) {
    // 如果是rgb格式，转换为16进制
    if (color.startsWith('rgb')) {
      const rgb = color.match(/\d+/g)
      if (rgb && rgb.length >= 3) {
        const hex = '#' + rgb.slice(0, 3).map(x => {
          const hex = parseInt(x).toString(16)
          return hex.length === 1 ? '0' + hex : hex
        }).join('')
        hostTypeForm.color = hex.toUpperCase()
      }
    } else if (color.startsWith('#')) {
      // 确保16进制格式正确
      hostTypeForm.color = color.toUpperCase()
    }
  }
}

// 生命周期
onMounted(() => {
  fetchHostTypes()
})
</script>

<style lang="scss" scoped>
// 使用全局透明玻璃样式，只保留必要的自定义样式

// 强制覆盖对话框样式，确保透明玻璃效果
:deep(.el-dialog) {
  background: rgba(255, 255, 255, 0.05) !important;
  border: 1px solid rgba(255, 255, 255, 0.1) !important;
  backdrop-filter: blur(20px) !important;
  box-shadow:
    0 8px 32px rgba(0, 0, 0, 0.3),
    inset 0 1px 0 rgba(255, 255, 255, 0.1) !important;

  .el-dialog__header {
    background: transparent !important;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1) !important;

    .el-dialog__title {
      color: white !important;
      text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3) !important;
    }

    .el-dialog__headerbtn .el-dialog__close {
      color: rgba(255, 255, 255, 0.8) !important;

      &:hover {
        color: #00eaff !important;
      }
    }
  }

  .el-dialog__body {
    background: transparent !important;
    color: white !important;
  }

  .el-dialog__footer {
    background: transparent !important;
    border-top: 1px solid rgba(255, 255, 255, 0.1) !important;
  }
}

// 表单样式
:deep(.el-form) {
  .el-form-item__label {
    color: rgba(255, 255, 255, 0.9) !important;
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3) !important;
  }

  .el-input__wrapper {
    background: rgba(255, 255, 255, 0.05) !important;
    border: 1px solid rgba(255, 255, 255, 0.1) !important;
    backdrop-filter: blur(10px) !important;
    box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1) !important;

    &:hover {
      border-color: rgba(0, 234, 255, 0.3) !important;
    }

    &.is-focus {
      border-color: #00eaff !important;
      box-shadow:
        inset 0 1px 3px rgba(0, 0, 0, 0.1),
        0 0 10px rgba(0, 234, 255, 0.3) !important;
    }

    .el-input__inner {
      color: white !important;
      background: transparent !important;

      &::placeholder {
        color: rgba(255, 255, 255, 0.5) !important;
      }
    }

    // 图标展示框样式
    .el-input__prepend {
      background: rgba(255, 255, 255, 0.08) !important;
      border: 1px solid rgba(255, 255, 255, 0.15) !important;
      backdrop-filter: blur(10px) !important;
      color: rgba(255, 255, 255, 0.9) !important;
      border-radius: 8px 0 0 8px !important;
      padding: 0 12px !important;
      display: flex !important;
      align-items: center !important;
      justify-content: center !important;
      min-width: 40px !important;
      position: relative !important;
      z-index: 2 !important;

      i {
        color: #00eaff !important;
        font-size: 16px !important;
        text-shadow: 0 0 8px rgba(0, 234, 255, 0.5) !important;
      }
    }
  }

  .el-textarea__inner {
    background: rgba(255, 255, 255, 0.05) !important;
    border: 1px solid rgba(255, 255, 255, 0.1) !important;
    color: white !important;
    backdrop-filter: blur(10px) !important;

    &::placeholder {
      color: rgba(255, 255, 255, 0.5) !important;
    }

    &:hover {
      border-color: rgba(0, 234, 255, 0.3) !important;
    }

    &:focus {
      border-color: #00eaff !important;
      box-shadow: 0 0 10px rgba(0, 234, 255, 0.3) !important;
    }
  }
}

// 通用按钮样式
:deep(.el-button) {
  background: rgba(255, 255, 255, 0.05) !important;
  border: 1px solid rgba(255, 255, 255, 0.1) !important;
  color: white !important;
  backdrop-filter: blur(10px) !important;
  transition: all 0.3s ease !important;

  &:hover {
    background: rgba(255, 255, 255, 0.1) !important;
    border-color: rgba(0, 234, 255, 0.3) !important;
    transform: translateY(-1px) !important;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2) !important;
  }

  &.el-button--primary {
    background: linear-gradient(135deg, #00eaff, #0099cc) !important;
    border-color: #00eaff !important;
    box-shadow: 0 4px 15px rgba(0, 234, 255, 0.3) !important;

    &:hover {
      background: linear-gradient(135deg, #33f0ff, #00b8e6) !important;
      box-shadow: 0 6px 20px rgba(0, 234, 255, 0.4) !important;
    }
  }

  &.el-button--danger {
    background: linear-gradient(135deg, #ff6b6b, #ee5a52) !important;
    border-color: #ff6b6b !important;
    box-shadow: 0 4px 15px rgba(255, 107, 107, 0.3) !important;

    &:hover {
      background: linear-gradient(135deg, #ff8a80, #f44336) !important;
      box-shadow: 0 6px 20px rgba(255, 107, 107, 0.4) !important;
    }
  }
}

.color-display {
  display: flex;
  align-items: center;
  gap: 8px;
}

.color-box {
  width: 20px;
  height: 20px;
  border-radius: 4px;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.color-text {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.8);
}

// 操作按钮样式 - 直接复制主机管理页面的样式
.action-buttons {
  display: flex;
  gap: 4px;
  flex-wrap: nowrap;
  justify-content: center;
  align-items: center;

  .action-btn {
    min-width: 28px !important;
    width: 28px !important;
    height: 28px !important;
    padding: 0 !important;
    border-radius: 6px !important;
    font-size: 12px !important;
    display: flex !important;
    align-items: center !important;
    justify-content: center !important;

    // 按钮颜色
    &.el-button--primary {
      background: linear-gradient(135deg, #409eff, #5dade2) !important;
      border-color: #409eff !important;
      color: white !important;

      &:hover {
        background: linear-gradient(135deg, #66b1ff, #7bb8e6) !important;
        transform: translateY(-1px) !important;
        box-shadow: 0 4px 12px rgba(64, 158, 255, 0.4) !important;
      }
    }

    &.el-button--info {
      background: linear-gradient(135deg, #909399, #a6a9ad) !important;
      border-color: #909399 !important;
      color: white !important;

      &:hover {
        background: linear-gradient(135deg, #a6a9ad, #b1b3b8) !important;
        transform: translateY(-1px) !important;
        box-shadow: 0 4px 12px rgba(144, 147, 153, 0.4) !important;
      }
    }

    &.el-button--success {
      background: linear-gradient(135deg, #67c23a, #85ce61) !important;
      border-color: #67c23a !important;
      color: white !important;

      &:hover {
        background: linear-gradient(135deg, #85ce61, #95d475) !important;
        transform: translateY(-1px) !important;
        box-shadow: 0 4px 12px rgba(103, 194, 58, 0.4) !important;
      }
    }

    &.el-button--warning {
      background: linear-gradient(135deg, #e6a23c, #ebb563) !important;
      border-color: #e6a23c !important;
      color: white !important;

      &:hover {
        background: linear-gradient(135deg, #ebb563, #f0c78a) !important;
        transform: translateY(-1px) !important;
        box-shadow: 0 4px 12px rgba(230, 162, 60, 0.4) !important;
      }
    }

    &.el-button--danger {
      background: linear-gradient(135deg, #f56c6c, #f78989) !important;
      border-color: #f56c6c !important;
      color: white !important;

      &:hover {
        background: linear-gradient(135deg, #f78989, #f9a7a7) !important;
        transform: translateY(-1px) !important;
        box-shadow: 0 4px 12px rgba(245, 108, 108, 0.4) !important;
      }
    }

    i {
      font-size: 12px !important;
      margin: 0 !important;
    }
  }
}

.icon-selector {
  width: 100%;
}

.icon-grid {
  display: grid;
  grid-template-columns: repeat(10, 1fr);
  gap: 8px;
  margin-top: 10px;
  max-height: 200px;
  overflow-y: auto;
  padding: 10px;
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 4px;
  background: rgba(255, 255, 255, 0.05);
  backdrop-filter: blur(10px);
}

.icon-option {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  background: rgba(255, 255, 255, 0.05);
  color: rgba(255, 255, 255, 0.8);

  &:hover {
    border-color: rgba(0, 234, 255, 0.5);
    background: rgba(0, 234, 255, 0.1);
    color: #00eaff;
  }

  &.active {
    border-color: #00eaff;
    background: rgba(0, 234, 255, 0.2);
    color: #00eaff;
  }
}

.color-selector {
  display: flex;
  align-items: center;
}

.form-tip {
  margin-top: 5px;
  font-size: 12px;
  color: rgba(255, 255, 255, 0.6);
  display: flex;
  align-items: center;
  gap: 5px;

  i {
    color: #00eaff;
  }
}


</style>
